package cases

import (
	"errors"
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"xpms/app/models"
	"xpms/cores"
	"xpms/cores/utils"
)

type TestCasePkgCase struct {
	Id       int64 `orm:"pk;column(id);" json:"Id,string"`
	Pkgid    int64 `json:"Pkgid,string"`
	Caseid   int64 `json:"Caseid,string"`
	Name     string
	Type     int64
	Degree   int64
	Created  int64
	Createid int64 `json:"Createid,string"`
	Status   int
	Changed  int64
	Changeid int64 `json:"Changid,string"`
	Sort     int64 `json:"Sort,string"`
	Version  int64 `json:"Version,string"`
	Remarks  string
}

func (this *TestCasePkgCase) TableName() string {
	return models.TableName("projects_test_pkg_case")
}

func init() {
	orm.RegisterModel(new(TestCasePkgCase))
}

/**
批量保存和更新
*/
func AddPkgCases(userid int64, upd AddCasePkgCaseDto) error {
	var err error
	condArr := make(map[string]interface{})
	condArr["ids"] = upd.Caseid
	ops := CaseNoPageExec(condArr)
	if len(ops) == 0 {
		return errors.New("没有对应的用例编号")
	}
	var u []TestCasePkgCase
	utils.UUID.Init(1024)
	for _, v := range ops {
		id, _ := utils.UUID.GetId()
		pkgCase := new(TestCasePkgCase)
		utils.SimpleCopyProperties(pkgCase, v)
		pkgCase.Id = id
		pkgCase.Caseid = v.Id
		pkgCase.Changeid = userid
		pkgCase.Changed = time.Now().Unix()
		pkgCase.Pkgid = upd.Pkgid
		u = append(u, *pkgCase)
	}
	o := orm.NewOrm()
	_, err = o.InsertMulti(100, u)
	return err
}

/**
批量删除
*/
func DelPkgCases(ids []int64) error {
	var err error
	o := orm.NewOrm()
	param := make([]interface{}, 0, 0)
	sql := `"DELETE pms_projects_test_pkg_case WHERE `
	if !utils.IsEmpty(ids) {
		sql = sql + ` id in(`
		sql1, value := cores.SqlInParam(ids)
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	_, err = o.Raw(sql, param).Exec()
	return err
}

func PkgCasePageExec(condArr map[string]interface{}, page int, offset int) []TestCasePkgCase {
	o := orm.NewOrm()
	var dto []TestCasePkgCase
	o.Raw(pkgCasePageSql(condArr, 1, page, offset)).QueryRows(&dto)
	return dto
}

func PkgCaseNoPageExec(condArr map[string]interface{}) []TestCasePkgCase {
	o := orm.NewOrm()
	var dto []TestCasePkgCase
	o.Raw(pkgCasePageSql(condArr, 1, 1, 10000)).QueryRows(&dto)
	return dto
}
func PkgCasePageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var Dto int64
	o.Raw(pkgCasePageSql(condArr, 0, page, offset)).QueryRow(&Dto)
	return Dto
}

/**
  组装sql
*/
func pkgCasePageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
		SELECT
		  pc.*
		FROM  pms_projects_test_pkg_case pc
      WHERE 1 = 1 `
	param := make([]interface{}, 0, 0)

	if !utils.IsEmpty(condArr["pkgid"]) {
		sql = sql + ` and  pc.pkgid in(`
		sql1, value := cores.SqlInParam(condArr["pkgid"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	if !utils.IsEmpty(condArr["caseid"]) {
		sql = sql + ` and  pc.caseid=?`
		param = append(param, condArr["caseid"])
	}
	if !utils.IsEmpty(condArr["id"]) {
		sql = sql + ` and  pc.id=?`
		param = append(param, condArr["id"])
	}
	if !utils.IsEmpty(condArr["keyword"]) {
		sql = sql + ` and  pc.name LIKE concat('%',?,'%')`
		param = append(param, condArr["keyword"])
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` order by created desc LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}

type TestPkgCaseVo struct {
	Id            int64 `json:"Id,string"`
	Projectid     int64 `json:"Projectid,string"`
	Projectname   string
	Moduleid      int64 `json:"Moduleid,string"`
	Modulename    int64 `json:"Modulename,string"`
	Pkgid         int64 `json:"Pkgid,string"`
	Pkgname       int64 `json:"Pkgname,string"`
	Name          string
	Type          string
	Degree        string
	Acceptid      int64 `json:"Acceptid,string"`
	Version       int64 `json:"Version,string"`
	Preconditions string
	Remarks       string
	Attachment    string
	Created       int64
	Createid      int64 `json:"Createid,string"`
	Status        int
	Changed       int64
	Changid       int64 `json:"Changid,string"`
	Acceptname    string
}

func CaseByPkg(condArr map[string]interface{}) []TestPkgCaseVo {
	o := orm.NewOrm()
	var dto []TestPkgCaseVo
	o.Raw(caseByPkgSql(condArr)).QueryRows(&dto)
	return dto
}

/**
  组装sql
*/
func caseByPkgSql(condArr map[string]interface{}) (string, []interface{}) {
	var sql string
	sql = `
		SELECT
		  tc.*
		FROM pms_projects_test_pkg_case pc
		  INNER JOIN pms_projects_test_case tc ON tc.caseid=pc.caseid
		  INNER JOIN pms_projects_test_case_pkg pkg ON pkg.id=pc.pkgid
      WHERE 1 = 1 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["pkgid"]) {
		sql = sql + ` and pc.pkgid in(`
		sql1, value := cores.SqlInParam(condArr["pkgid"])
		sql = sql + sql1 + `)`
		param = append(param, value...)
	}
	return sql, param
}
